/*
 * Copyright (C) 2012 Tapas Mobile Ltd.  All Rights Reserved.
 */

package com.tools.cleanmaster.taskmain;

import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.graphics.drawable.Drawable;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.appinfo.AppInfoCompat;
import com.tools.cleanmaster.utils.MemoryUtils;

import java.io.Serializable;
import java.util.ArrayList;

public class ProcessItem implements Serializable, Comparable<ProcessItem> {
    private static final long serialVersionUID = 7812261183770300071L;

    public String pkgName;
    public String label;
    public Drawable icon;
    public boolean foreground;
    public boolean checked = true;
    public boolean sys;
    public ArrayList<Integer> pids = new ArrayList<Integer>();
    public boolean isSelf = false;
    public boolean isSuggestedProtected = false;
    public int uid; // user id

    public boolean isValid() {
        return pkgName != null && label != null && icon != null;
    }

    public void addPid(int pid) {
        if (!pids.contains(pid)) {
            pids.add(pid);
        }
    }

    public int[] getPidArray() {
        int size = pids.size();
        int[] ret = new int[size];
        for (int pid : pids) {
            ret[--size] = pid;
        }
        return ret;
    }

    public void init(String pkgname, RunningAppProcessInfo amProcess) {
        pkgName = pkgname;
        foreground = (amProcess.importance >= RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && amProcess.importance <= RunningAppProcessInfo.IMPORTANCE_VISIBLE);
    }

    public void init(AppInfoCompat appInfo, RunningAppProcessInfo amProcess) {
        init(appInfo.pkgName, amProcess);
        label = appInfo.getLabel();
        icon = appInfo.getIcon();
        sys = appInfo.isSystem();
    }

    public void init(String pkgname, RunningServiceInfo amService) {
        pkgName = pkgname;
        foreground = amService.foreground;
    }

    public void init(AppInfoCompat appInfo, RunningServiceInfo amService) {
        init(appInfo.pkgName, amService);
        label = appInfo.getLabel();
        icon = appInfo.getIcon();
        sys = appInfo.isSystem();
    }

    // 根据占用内存大小排序
    @Override
    public int compareTo(ProcessItem another) {
        if (another == null) {
            return 0;
        }
        long mRam = MemoryUtils.getProcessAvailableRam(CleanApplication.getInstance(), this);
        long anotherRam = MemoryUtils.getProcessAvailableRam(CleanApplication.getInstance(), another);
        if (mRam > anotherRam) {
            return -1;
        } else if (mRam < anotherRam) {
            return 0;
        } else {
            return 0;
        }
    }
}
